package cn.sinata.wanglin.mine.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.view.WheelTime;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.CropImageActivity;
import com.xilada.xldutils.activitys.ImagePagerActivity;
import com.xilada.xldutils.activitys.SelectPhotoDialog;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.SpacesItemDecoration;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.FileUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.xldUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.aliyunoss.OssBean;
import cn.sinata.wanglin.aliyunoss.UpLoadImageUtils;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.mine.activity.AlterAutographActivity;
import cn.sinata.wanglin.mine.activity.AlterLableActivity;
import cn.sinata.wanglin.mine.activity.AlterindustryActivity;
import cn.sinata.wanglin.mine.activity.AlternicknameActivity;
import cn.sinata.wanglin.mine.activity.AuthenticationActivity;
import cn.sinata.wanglin.mine.activity.MyphotosActivity;
import cn.sinata.wanglin.mine.myinterface.MineDataInterface;
import cn.sinata.wanglin.model.Imageinfo;
import cn.sinata.wanglin.model.Lableinfo;
import cn.sinata.wanglin.model.Userinfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.village.activity.AllUserInfoActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * description：我的---个人信息
 * Created by kaihongwu on 2016/12/06 上午 9:45
 */
public class PersonInfoFragment extends BaseLazyFragment implements AppBarLayout.OnOffsetChangedListener{
    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
//    认证列表 (1:有房认证，2：有车认证，3:学历认证，4:事业认证)
    @BindView(R.id.iv_approve1)
    TextView iv_approve1;
    @BindView(R.id.iv_approve2)
    TextView iv_approve2;
    @BindView(R.id.iv_approve3)
    TextView iv_approve3;
    @BindView(R.id.iv_approve4)
    TextView iv_approve4;
    @BindView(R.id.tv_phone)
    TextView tv_phone;//电话号码
    @BindView(R.id.tv_sign)
    TextView tv_sign;//签名
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;//昵称
    @BindView(R.id.tv_sex)
    TextView tv_sex;//性别
    @BindView(R.id.tv_birthday)
    TextView tv_birthday;//出身年月日
    @BindView(R.id.tv_industry)
    TextView tv_industry;//行业
    @BindView(R.id.tv_belonglable)
    TextView tv_belonglable;//归属标签
    @BindView(R.id.rv_alllable)
    RecyclerView rv_alllable;//所有的标签
    @BindView(R.id.rv_allphoto)
    RecyclerView rv_allphoto;//所有的相册
    BaseRecyclerAdapter allphotoAdapter;
    BaseRecyclerAdapter alllableAdapter;
    private ArrayList<Lableinfo> malllabledatas=new ArrayList<>();
    private ArrayList<Imageinfo> mImageinfos=new ArrayList<>();
    private  ArrayList<String> mItems;
    private MineDataInterface mMineDataInterface;
    private Userinfo mUserInfo;

    public void addMineDataInterface(MineDataInterface mMineDataInterface) {
        this.mMineDataInterface=mMineDataInterface;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_personinfo;
    }

    @Override
    protected void onFirstVisibleToUser() {

        addOnOffsetChangeListener();
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Fragment fragment = getParentFragment();
                if (fragment != null && !fragment.isDetached() && fragment instanceof MineFragment) {
                    ((MineFragment) fragment).getUserinfo();
                }
            }
        });

        if(alllableAdapter==null) {
            GridLayoutManager mgr = new GridLayoutManager(getActivity(), 3);
            rv_alllable.setLayoutManager(mgr);
            alllableAdapter = new BaseRecyclerAdapter<Lableinfo>(malllabledatas, R.layout.item_personalllable) {
                @Override
                public void onBind(final int position, final Lableinfo data, ViewHolder holder) {
                    holder.setText(R.id.tv_mylable, data.getName());
                }
            };
            rv_alllable.setAdapter(alllableAdapter);
        }
        if(allphotoAdapter==null){
            mImageinfos.add(new Imageinfo("-1"));
            rv_allphoto.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
            rv_allphoto.addItemDecoration(new SpacesItemDecoration(3));
            allphotoAdapter= new BaseRecyclerAdapter<Imageinfo>(mImageinfos, R.layout.item_myimage_grid_nodelete) {
                @Override
                public void onBind(final int position, final Imageinfo data, ViewHolder holder) {
                    if("-1".equals(data.getImgID())){
                        ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("res://mipmap/"+R.mipmap.ic_addimage));
                         holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mImageinfos.remove(0);
                                ActivityUtil.create(PersonInfoFragment.this).go(MyphotosActivity.class).put("mImageinfos",mImageinfos)
                                        .startForResult(23);
                            }
                        });
                    }else{
                        ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(data.getImgUrl());
                         holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                int current=position;
                                ArrayList<String> showPhoto=new ArrayList<>();
                                for(int i=0;i<mImageinfos.size();i++){
                                    if(!"-1".equals(mImageinfos.get(i).getImgID())){
                                        showPhoto.add(mImageinfos.get(i).getImgUrl());
                                    }else{
                                        current--;
                                    }

                                }
                                ActivityUtil.create(PersonInfoFragment.this).go(ImagePagerActivity.class)
                                        .put(ImagePagerActivity.URLS,showPhoto)
                                        .put(ImagePagerActivity.CURRENT_POSITION,current)
                                        .start();
                            }
                        });

                    }

                }
            };
            allphotoAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {

                }
            });
            rv_allphoto.setAdapter(allphotoAdapter);
        }

    }



    @Override
    protected void onVisibleToUser() {
        addOnOffsetChangeListener();
    }

    @Override
    protected void onInvisibleToUser() {
        removeOnOffsetChangeListener();
    }

    @OnClick({R.id.ly_perinfo_alternickname,
            R.id.ly_perinfo_borntime,R.id.ly_perinfo_sex,
            R.id.ly_perinfo_achieve, R.id.ly_perinfo_industry,
            R.id.ly_perinfo_lable,R.id.ly_perinfo_autograph})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_perinfo_alternickname:
                //描述:修改昵称
                String  nickname= tv_nickname.getText().toString();
                ActivityUtil.create(this).go(AlternicknameActivity.class).put("nickname",nickname)
                        .startForResult(1);
                break;
            case R.id.ly_perinfo_borntime:
                //描述:修改出生年月
                choiceBornTime();
                break;
            case   R.id.ly_perinfo_sex:
                //描述:修改性别
                choiceSex();
                break;
            case   R.id.ly_perinfo_achieve:
                //描述:成就认证
                boolean isHaveHouse=false;
                boolean isHaveCar=false;
                boolean isHaveEdu=false;
                boolean isHaveCareer=false;
                if (mUserInfo!=null&&mUserInfo.getApproveList()!=null) {
                    isHaveHouse = mUserInfo.getApproveList().contains("A");
                    isHaveCar = mUserInfo.getApproveList().contains("B");
                    isHaveEdu = mUserInfo.getApproveList().contains("C");
                    isHaveCareer = mUserInfo.getApproveList().contains("D");
                }
                ActivityUtil.create(this).go(AuthenticationActivity.class)
                        .put("isHaveHouse",isHaveHouse)
                        .put("isHaveCar",isHaveCar)
                        .put("isHaveEdu",isHaveEdu)
                        .put("isHaveCareer",isHaveCareer)
                        .start();
                break;
            case    R.id.ly_perinfo_industry:
                //描述:修改行业
                String industry=tv_industry.getText().toString();
                ActivityUtil.create(this).go(AlterindustryActivity.class).put("industry",industry)
                        .startForResult(2);
                break;
            case     R.id.ly_perinfo_lable:
                //描述:修改标签
                String belonglable=tv_belonglable.getText().toString();
                ActivityUtil.create(this).go(AlterLableActivity.class)
                        .put("belonglable",belonglable)
                        .put("otherlable",malllabledatas)
                        .startForResult(3);
                break;

            case   R.id.ly_perinfo_autograph:
                //描述:修改个性签名
               String signcontent= tv_sign.getText().toString();
                ActivityUtil.create(this).go(AlterAutographActivity.class).put("signcontent",signcontent)
                        .startForResult(4);
                break;


        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Utils.systemErr("=resultCode==="+resultCode);
        Utils.systemErr("=requestCode==="+requestCode);
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==-1){
            switch (requestCode){
                case 1://修改昵称
                    if (data!=null){
                        String nickname=data.getStringExtra("nickname");
                        tv_nickname.setText(nickname);
                        mMineDataInterface.onRefresh(2);
                    }
                    break;
                case 2://修改行业
                    if (data!=null){
                        String industry=data.getStringExtra("industry");
                        tv_industry.setText(industry);
                    }
                    break;
                case 3://修改标签
                    if (data!=null){

                        String belongLabel=data.getStringExtra("belongLabel");
                        if(!TextUtils.isEmpty(belongLabel)){
                            tv_belonglable.setText(belongLabel);
                            tv_belonglable.setVisibility(View.VISIBLE);
                        }
                        malllabledatas.clear();
                        String otherLabel=data.getStringExtra("otherLabel");
                        String[] sourceStrArray =otherLabel.split(",");
                        for(int i=0;i<sourceStrArray.length;i++){
                            malllabledatas.add(new Lableinfo(sourceStrArray[i],true));
                        }
                        alllableAdapter.notifyDataSetChanged();
                    }
                    break;
                case 4://修改个性签名
                    if (data!=null){
                        String signcontent=data.getStringExtra("signcontent");
                        tv_sign.setText(signcontent);
                    }
                    break;
                case 5:
                    if (data!=null){
                        String path = data.getStringExtra(SelectPhotoDialog.DATA);
                        cropImage(path);
                    }
                    break;
                case 6:
                    if (data!=null){
                        String path = data.getStringExtra("path");
                        updateHead(path);
                    }
                    break;
            }

        }
        if(requestCode==23){
            mMineDataInterface.onRefresh(0);
        }
    }
    private void cropImage(String path){
        ActivityUtil.create(this).go(CropImageActivity.class)
                .put("uri",path)
                .put("mode",1)
                .startForResult(6);
    }

    private void updateHead(final String path){
             Utils.systemErr("-path-->"+path);
             final ArrayList<OssBean>  mOssBeans=new ArrayList<>();
             mOssBeans.add(new OssBean(path));
             Observable<List<OssBean>> mObservable= new  UpLoadImageUtils(mOssBeans).uploadimg();
             mObservable.doOnSubscribe(new Action0() {
             @Override
             public void call() {
                showDialog("上传中...");
              }
              })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OssBean>>() {
                    @Override
                    public void onCompleted() {
                        dismissDialog();
                    }
                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<OssBean> ossBeen) {
                        if(ossBeen!=null&&ossBeen.size()!=0){
                            alterUserinfo(ossBeen.get(0).getUrlkey(),Constant.ALT_headUrl);
                        }
                    }
                });


    }
    /**
     * 修改性别
     */
    private void choiceSex() {
        mItems = new ArrayList<>();
        mItems.add("男");
        mItems.add("女");
        OptionsPickerView pvOptions= new OptionsPickerView(getActivity());
        pvOptions.setPicker(mItems);
        pvOptions.setTitle("选择性别");
        //设置数据是否循环
        pvOptions.setCyclic(false);
        //监听确定选择按钮
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                alterUserinfo(""+options1,Constant.ALT_sex);
            }
        });
        pvOptions.show();
    }

    /**
     * 选择时间;
     */
    private void choiceBornTime() {
        //起始时间的选择
        TimePickerView  pvTime = new TimePickerView(getActivity(), TimePickerView.Type.YEAR_MONTH_DAY);
        // 创建 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        pvTime.setRange(WheelTime.DEFULT_START_YEAR,calendar.get(Calendar.YEAR));//要在setTime 之前才有效果哦
        calendar.set(1986,month,day);
        pvTime.setTime(calendar.getTime());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                alterUserinfo(getTime(date),Constant.ALT_birthday);
            }
        });
        pvTime.show();
    }
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd" );
        return format.format(date);
    }

    /**
     * 修改用户相关信息，除了标签以外
     * @param datamsg
     * @param tag
     */
    private  void alterUserinfo(final String datamsg,final int tag){
        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        Observable<ResultData<JsonObject>> observable = HttpManager.updUser(""+userid,datamsg,tag);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        showToast(msg);
                        switch (tag){
                            case Constant.ALT_birthday:
                                tv_birthday.setText(datamsg);
                                break;
                            case Constant.ALT_sex:
                                if("0".equals(datamsg)){
                                    tv_sex.setText("男");
                                    SharedPreferencesUtils.save(Constant.SP_SEX,datamsg);
                                    mMineDataInterface.onRefresh(3);
                                }else{
                                    tv_sex.setText("女");
                                    SharedPreferencesUtils.save(Constant.SP_SEX,datamsg);
                                    mMineDataInterface.onRefresh(3);
                                }

                                break;
                            case Constant.ALT_headUrl:
                                SharedPreferencesUtils.save(Constant.SP_HEADURL,datamsg);
//                                headview_mine.setImageURI(datamsg);
                                mMineDataInterface.onRefresh(1);

                                if (!TextUtils.isEmpty(xldUtils.PICDIR)) {
                                    FileUtils.deleteFiles(new File(xldUtils.PICDIR));
                                }
                                break;
                        }
                    }
                });

    }

    public void setDataForUser(Userinfo userinfo){
        mUserInfo = userinfo;
        if(!TextUtils.isEmpty(userinfo.getNickName())){
            tv_nickname.setText(userinfo.getNickName());
        }
        if(!TextUtils.isEmpty(userinfo.getSex())){
            if("1".equals(userinfo.getSex()))
            {
                tv_sex.setText("女");
            }else if("0".equals(userinfo.getSex())){
                tv_sex.setText("男");
            }
        }
        if(!TextUtils.isEmpty(userinfo.getPhone())){
            tv_phone.setText(userinfo.getPhone());
        }
        if(!TextUtils.isEmpty(userinfo.getBirthday())){
            tv_birthday.setText(userinfo.getBirthday());
        }
        if(!TextUtils.isEmpty(userinfo.getIndustry())){
            tv_industry.setText(userinfo.getIndustry());
        }
        if(!TextUtils.isEmpty(userinfo.getCharacter())){
            tv_sign.setText(userinfo.getCharacter());
        }

        if(!TextUtils.isEmpty(userinfo.getBelongLabel())){
            tv_belonglable.setText(userinfo.getBelongLabel());
            tv_belonglable.setVisibility(View.VISIBLE);
        }else{
            tv_belonglable.setVisibility(View.GONE);
        }
        malllabledatas.clear();
        if(!TextUtils.isEmpty(userinfo.getOtherLabel())){
            String[] sourceStrArray =userinfo.getOtherLabel().split(",");
            for(int i=0;i<sourceStrArray.length;i++){
                malllabledatas.add(new Lableinfo(sourceStrArray[i],true));
            }
        }
        alllableAdapter.notifyDataSetChanged();
        mImageinfos.clear();
        mImageinfos.add(new Imageinfo("-1"));
        if(userinfo.getImgList()!=null&&userinfo.getImgList().size()!=0){
            mImageinfos.addAll(userinfo.getImgList());
        }
        allphotoAdapter.notifyDataSetChanged();
        iv_approve1.setVisibility(View.VISIBLE);
        iv_approve2.setVisibility(View.VISIBLE);
        iv_approve3.setVisibility(View.VISIBLE);
        iv_approve4.setVisibility(View.VISIBLE);
        if(userinfo.getApproveList()!=null&&userinfo.getApproveList().size()!=0){
            Drawable drawable1 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_house3);
            if (userinfo.getApproveList().contains("A")) {
                if ("1".equals(userinfo.getOwnerAuthType())) {
                    drawable1 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_house1);
                } else if ("2".equals(userinfo.getOwnerAuthType())) {
                    drawable1 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_house2);
                } else {
                    drawable1 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_house0);
                }
            }
            iv_approve1.setCompoundDrawablesWithIntrinsicBounds(null,drawable1,null,null);
            Drawable drawable2=ContextCompat.getDrawable(context,R.mipmap.ic_auth_car0);
            if (userinfo.getApproveList().contains("B")) {
                drawable2 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_car);
            }
            iv_approve2.setCompoundDrawablesWithIntrinsicBounds(null,drawable2,null,null);
            Drawable drawable3=ContextCompat.getDrawable(context,R.mipmap.ic_auth_education0);
            if (userinfo.getApproveList().contains("C")) {
                drawable3 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_education);
            }
            iv_approve3.setCompoundDrawablesWithIntrinsicBounds(null,drawable3,null,null);
            Drawable drawable4=ContextCompat.getDrawable(context,R.mipmap.ic_auth_career0);
            if (userinfo.getApproveList().contains("D")) {
                drawable4 = ContextCompat.getDrawable(context,R.mipmap.ic_auth_career);
            }
            iv_approve4.setCompoundDrawablesWithIntrinsicBounds(null,drawable4,null,null);
        }
    }

    void addOnOffsetChangeListener(){
        if (getActivity() instanceof AllUserInfoActivity) {
            ((AllUserInfoActivity) getActivity()).addOnOffsetChangedListener(this);
        } else if (getParentFragment()!=null && getParentFragment() instanceof MineFragment) {
            ((MineFragment) getParentFragment()).addOnOffsetChangedListener(this);
        }
    }

    void removeOnOffsetChangeListener(){
        if (getActivity() instanceof AllUserInfoActivity) {
            ((AllUserInfoActivity) getActivity()).removeOnOffsetChangedListener(this);
        }else if (getParentFragment()!=null && getParentFragment() instanceof MineFragment) {
            ((MineFragment) getParentFragment()).removeOnOffsetChangedListener(this);
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset >= 0) {
            mSwipeRefreshLayout.setEnabled(true);
        } else {
            mSwipeRefreshLayout.setEnabled(false);
        }
    }

    public void setRefreshFinish() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }
}
